package com.scrum.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.scrum.managers.IUserSessionManager;
import com.scrum.repository.IUserRepository;
import com.scrum.vos.Confirmation;
import com.scrum.vos.ConfirmationState;
import com.scrum.vos.MessageExceptions;
import com.scrum.vos.User;

@Service
@Transactional
public class UserServices implements IUserServices{
	
	@Autowired
	IUserRepository userRepository;
	
	@Autowired
	IUserSessionManager userSessionManager;
	
	@Override
	public Confirmation createUser(User user) throws Exception{
				
		if(!this.validateCompleteData(user))
		{
			throw new Exception(MessageExceptions.COMPLETE_FIELDS);
		}
		
		if(!this.validateExistUser(user))
		{
			throw new Exception(MessageExceptions.USER_ALREADY_EXIST);
		}
		
		try {
			userRepository.saveUpdate(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Confirmation confirmation = new Confirmation();
		
		confirmation.setConfirmationState(ConfirmationState.OK);
		
		return confirmation;
	}

	@Override
	public String login(String nickName, String password) throws Exception{
		
		User user = userRepository.findUserByAttribute("nickName", nickName);
		
		if(!user.getPassword().equals(password))
		{
			throw new Exception(MessageExceptions.INVALID_PASSWORD);
		}
		
		return userSessionManager.loginUser(user);
	}

	@Override
	public void logout(String sessionToken) throws Exception {

		userSessionManager.logoutUser(sessionToken);
	}
	
	
	//VALIDAMOS QUE EL USUARIO NUEVO YA NO ESTE REGISTRADO
	private boolean validateExistUser(User user)
	{
		try {
			
			if(userRepository.findUserByAttribute("mail", user.getMail()) != null){
				return false;
			}
			
		} catch (Exception e) {

			try {
				if(userRepository.findUserByAttribute("nickName", user.getNickName()) != null){
					return false;
				}
			} catch (Exception e1) {
				return true;
			}
		}
		return false;
	}
	
	
	//VALICION DE CAMPOS COMPLETOS PARA EL REGISTRO
	private boolean validateCompleteData(User user)
	{
		if(user.getMail() == "" || user.getMail() == null)
		{
			return false;
		}
		
		if(user.getName() == "" || user.getName() == null)
		{
			return false;
		}
		
		if(user.getNickName() == "" || user.getNickName() == null)
		{
			return false;
		}
		
		if(user.getPassword() == "" || user.getPassword() == null)
		{
			return false;
		}
		
		if(user.getSurName() == "" || user.getSurName() == null)
		{
			return false;
		}		
		
		return true;
	}
	

}
